package c2.cross.business.championrace;

import cate.game.framework.common.compress.CompressedContent;
import cate.game.pvp.championrace.data.ChampionRaceOpponent;
import cate.game.pvp.championrace.data.ChampionRacePs;
import easy.java.dev.note.NoteField;
import org.springframework.data.annotation.Transient;

import java.util.*;
import java.util.stream.Collectors;


public class ChampionRacePsData {
    @NoteField("ps")
    private HashMap<String, ChampionRacePs> psMap;
    @Transient
    private final Object psLock = new Object();

    public void initialize() {
        if (psMap == null) {
            psMap = new HashMap<>();
        }
    }

    public ChampionRacePs findPs(String roleUid) {
        return psMap.get(roleUid);
    }

    public List<ChampionRaceOpponent> findPs(int srvId) {
        List<ChampionRaceOpponent> psList;
        synchronized (psLock) {
            psList = psMap.values()
                    .stream()
                    .map(ChampionRacePs::getOpponent)
                    .filter(opp -> opp.getSnapshot().base.srvId == srvId)
                    .collect(Collectors.toList());
        }
        return psList;
    }

    public List<ChampionRacePs> getSortedPs(Comparator<? super ChampionRacePs> comparator) {
        List<ChampionRacePs> psList;
        synchronized (psLock) {
            psList = psMap.values()
                    .stream()
                    .sorted(comparator)
                    .collect(Collectors.toList());
        }
        return psList;
    }

    public void addPsList(List<ChampionRacePs> psList) {
        synchronized (psLock) {
            for (ChampionRacePs ps : psList) {
                psMap.put(ps.getUid(), ps);
            }
        }
    }

    public void updatePs(ChampionRacePs ps) {
        synchronized (psLock) {
            ChampionRacePs eps = psMap.get(ps.getUid());
            if (Objects.nonNull(eps)) {
                eps.getOpponent().setSnapshot(ps.getOpponent().getSnapshot().copy());
                LinkedList<CompressedContent> cpsList = eps.getCpsList();
                cpsList.addAll(ps.getCpsList());
            } else {
                psMap.put(ps.getUid(), ps);
            }
        }
    }

    public void clear() {
        synchronized (psLock) {
            psMap.clear();
        }
    }
}
